package com.valuedaas.schoolsafety.common.filter;

import com.valuedaas.schoolsafety.common.Constants;
import com.valuedaas.schoolsafety.common.ErrorCodes;
import com.valuedaas.schoolsafety.common.base.Result;
import com.valuedaas.schoolsafety.util.WebUtil;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 除去几个 不需要登录就可访问的接口， 其他接口都需要session才能访问
 */
@Component
@WebFilter(filterName = "sessionFilter", urlPatterns = "*.do")
@Order(1)
public class SessionFilter extends OncePerRequestFilter {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SessionFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain chain) throws ServletException, IOException {
        String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        if (url.startsWith("/") && url.length() > 1) {
            url = url.substring(1);
        }
        if(WebUtil.isSwaggerResources(url)){ //跳过swagger 资源
            chain.doFilter(httpRequest, httpResponse);
            return;
        }
        if (WebUtil.isNoNeedPermission(url)) { //跳过不需要验证的资源
            chain.doFilter(httpRequest, httpResponse);
            return;
        } else {
            HttpSession session = httpRequest.getSession();
            if (session.getAttribute(Constants.SESSION_KEY) != null) {
                // session存在
                chain.doFilter(httpRequest, httpResponse);
                return;
            } else {
                responseJson(ErrorCodes.SESSION_TIMEOUT, "身份过期", httpResponse);
                return;
            }
        }

    }

    private void responseJson(int code, String message, HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.print(Result.error(code, message, null));
        pw.flush();
    }



}
